package com.meta.api.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.meta.api.param.UserNamePwdParam;
import com.meta.api.po.UserModel;
import com.meta.api.service.UserServiceQuery;
import com.meta.api.service.UserServiceUpdate;
import com.meta.common.enums.LoginTypeConstants;
import com.meta.common.vo.ResponseInfo;
import java.io.Serializable;
import java.util.UUID;

/**
 * @Author: xieZW
 * @Date: 2021/11/9 14:44
 */
@RestController
@RequestMapping("api")
public class LoginController {

    private static Logger log = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserServiceQuery userServiceQuery;

    @Autowired
    private UserServiceUpdate userServiceUpdate;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public ResponseInfo login(@RequestBody UserNamePwdParam param) {
        try {
            log.info("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
            String username = param.getUsername();
            String password = param.getPassword();
            if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
                return ResponseInfo.error("用户名或密码不能为空！");
            }
            ShiroLoginM(param);
            Subject subject = SecurityUtils.getSubject();
            Object principal = subject.getPrincipal();
            System.out.println("principal = " + principal);
            JSONObject jsonObject = new JSONObject();
            Serializable id = subject.getSession().getId();
            jsonObject.put("token", id);
            jsonObject.put("data", principal);
            return ResponseInfo.succ(jsonObject);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseInfo.error(e.getMessage());
        }
    }

    private void ShiroLoginM(@RequestBody UserNamePwdParam param) {
        //存入shiro
        Subject currentSubject = SecurityUtils.getSubject();
        if (currentSubject != null) {
            currentSubject.logout();
        }
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken();
        usernamePasswordToken.setUsername(param.getUsername());
        usernamePasswordToken.setPassword(param.getPassword().toCharArray());
        usernamePasswordToken.setHost(LoginTypeConstants.login);
        currentSubject.login(usernamePasswordToken);
    }

    @PostMapping("/login_auth")
    public ResponseInfo login_auth(@RequestBody UserNamePwdParam userNamePwdParam) {
        try {
            log.info("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
            String username = userNamePwdParam.getUsername();
            String password = userNamePwdParam.getPassword();
            if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
                return ResponseInfo.error("用户名或密码不能为空！");
            }
            UserModel login = userServiceQuery.login(userNamePwdParam);
            String token = UUID.randomUUID().toString();
            login.setToken(token);
            redisTemplate.opsForValue().set(token, login.getUserId().toString());
            return ResponseInfo.succ(login);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseInfo.error(e.getMessage());
        }
    }

    @PostMapping("/register")
    public ResponseInfo register(@RequestBody UserNamePwdParam userNamePwdParam){
        try {
            String username = userNamePwdParam.getUsername();
            String password = userNamePwdParam.getPassword();
            String email = userNamePwdParam.getEmail();
            if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(email)) {
                return ResponseInfo.error("缺少必要参数");
            }
            return ResponseInfo.succ(userServiceUpdate.register(userNamePwdParam));
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return ResponseInfo.error();
        }
    }

}
